package com.mobile.framework.util;

import java.util.StringTokenizer;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * Spring application context Util
 */
public class SpringContextUtil {

	private static SpringContextUtil instance = null;

	private ApplicationContext ctx = null;

	private final String CONFIG_NAME = "spring.context.config";

	// 格式:/applicationContext.xml,/applicationContext-dataSourceJDBC.xml,/applicationContext-hibernate.xml
	private Log log = LogFactory.getLog(getClass().getName());

	/**
	 * 构造方法
	 */
	private SpringContextUtil() {
		String springConfig = Config.getProperty(CONFIG_NAME);
		if (!"".equals(springConfig)) {
			StringTokenizer st = new StringTokenizer(springConfig, ",");
			String[] paths = new String[st.countTokens()];
			int i = 0;
			while (st.hasMoreTokens()) {
				paths[i++] = st.nextToken();
			}
			long start = System.currentTimeMillis();
			ctx = new ClassPathXmlApplicationContext(paths);
			long end = System.currentTimeMillis();
			log.debug("ApplicationContext is inited ,spend " + (end - start)
					+ " ms");
		}
	}

	/**
	 * 初始化
	 * 
	 * 
	 */
	public static void init() {
		if (null == instance) {
			instance = new SpringContextUtil();
		}
	}

	/**
	 * 取得ApplicationContext
	 * 
	 * @return ApplicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		if (null == instance) {
			init();
		}
		return instance.ctx;
	}

	/**
	 * 取得Spring Bean 对象
	 * 
	 * @param bean
	 * @return Object
	 */
	public static Object getBean(String bean) {
		if (null == instance) {
			init();
		}
		ApplicationContext ctx1 = instance.ctx;
		if (null == ctx1) {
			return null;
		}
		return ctx1.getBean(bean);
	}
}
